package com.jxt.myjxtmanager;

import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jxt.myjxtmanager.db.SaleUser;
import com.jxt.myjxtmanager.db.SaleUserModel;
import com.jxt.myjxtmanager.puth.ExampleUtil;
import com.jxt.myjxtmanager.ui.activity.MyInfoActivity;
import com.jxt.myjxtmanager.ui.fragment.HomeFragment;
import com.jxt.myjxtmanager.ui.fragment.MineFragment;
import com.jxt.myjxtmanager.utils.LogUtils.LogInfo;
import com.jxt.myjxtmanager.utils.imageloader.ImageLoaderAbs;
import com.jxt.myjxtmanager.views.TabIconView;
import com.jxt.myjxtmanager.views.WrapContentHeightViewPager;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.MultiActionsNotificationBuilder;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends BaseActivity {

    private WrapContentHeightViewPager mPager;

    TabIconView currentImage;
    private TextView tv_driver_tel;
    public static boolean isForeground = false;
    private ImageView iv_avatar_info;
    /**
     * 图片资源
     */
    private int mIconRes[][] = {
            {R.drawable.ic_tab_main_crm, R.drawable.ic_tab_main_crm_light}, // TODO: 16-11-10 临时添加的伪图片
//            {R.drawable.img_phone, R.drawable.img_psw},
//            {R.drawable.img_phone, R.drawable.img_psw},
            {R.drawable.ic_tab_main_mine, R.drawable.ic_tab_main_mine_light}};

    private int[] mTabIds = {
            R.id.tab_icon_view_one,   //
//            R.id.tab_icon_view_two,   //
//            R.id.tab_icon_view_three, //
            R.id.tab_icon_view_four}; // 我的
    /**
     * tab 集合
     */
    private List<TabIconView> mTabIndicator = new ArrayList<TabIconView>();

    @SuppressWarnings("rawtypes")
    private Class[] fragments = {
            HomeFragment.class,
            MineFragment.class};
    private CollapsingToolbarLayout collapsingToolbar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        tv_driver_tel = (TextView) findViewById(R.id.tv_driver_tel);
        iv_avatar_info = (ImageView) findViewById(R.id.iv_avatar_info);
        iv_avatar_info.setOnClickListener(this);
        SaleUser saleUser = SaleUserModel.getInstance().loadCurrentSaleUsers();
        if (saleUser != null && !TextUtils.isEmpty(saleUser.getTrue_name())) {

            testMaterialDesign(saleUser.getTrue_name());
        }
        if (saleUser != null && !TextUtils.isEmpty(saleUser.getPhone())) {
            tv_driver_tel.setText(saleUser.getPhone());
        }

        mPager = (WrapContentHeightViewPager) findViewById(R.id.content);
        for (int i = 0; i < mTabIds.length; i++) {
            TabIconView tab = (TabIconView) findViewById(mTabIds[i]);
            tab.setOnClickListener(this);
            tab.init(mTabIds.length, 48, mIconRes[i][0], mIconRes[i][1]);
            mTabIndicator.add(tab);
            if (i == 0) {
                tab.transformPage(0);
                currentImage = tab;
            }
        }
        registerMessageReceiver();  // used for receive msg
        init();
    }

    protected void initData() {
        mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        mPager.setOnPageChangeListener(new PageChangeListener());
        mPager.setOffscreenPageLimit(2);
        mPager.setCurrentItem(0);
//        httpCheckUpdate(null);
        setTag();
        setAlias();
        setStyleBasic();
        setStyleCustom();
        setAddActionsStyle();
    }

    private void testMaterialDesign(String driverName) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
//        toolbar.setNavigationIcon(R.drawable.ic_left_return);

        collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle(driverName);
    }

    @Override
    public void onClick(View v) {
        currentImage.transformPage(1);
        switch (v.getId()) {
            case R.id.tab_icon_view_one:
                mPager.setCurrentItem(0, false);
                currentImage = mTabIndicator.get(0);
                break;
            case R.id.tab_icon_view_four:
                mPager.setCurrentItem(1, false);
                currentImage = mTabIndicator.get(1);
                break;
            case R.id.iv_avatar_info:
                startActivity(new Intent(MainActivity.this, MyInfoActivity.class));
                break;
        }
        currentImage.transformPage(0);
    }

    /**
     * viewPager 监听事件
     *
     * @author
     */
    class PageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageSelected(int position) {
            currentImage = mTabIndicator.get(position);
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int arg2) {
            if (positionOffset > 0f && mTabIndicator.size() > position - 1) {
                // draw icon alpha
                mTabIndicator.get(position + 1).transformPage(1 - positionOffset);
                mTabIndicator.get(position).transformPage(positionOffset);
            }
        }

    }

    @SuppressWarnings("unchecked")
    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return BaseFragment.newInstance(fragments[position]);
        }

        @Override
        public int getCount() {
            return fragments.length;
        }

    }


    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        JPushInterface.init(getApplicationContext());
    }


    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        SaleUser user = SaleUserModel.getInstance().loadCurrentSaleUsers();
        if (user == null) return;
        if (!TextUtils.isEmpty(user.getHead_img())) {
            ImageLoaderAbs.getInstance().roundDisplayImage(
                    user.getHead_img(), iv_avatar_info,
                    R.drawable.icon_headportrait);
        }
        if (collapsingToolbar == null) {
            collapsingToolbar =
                    (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        }
        collapsingToolbar.setTitle(user.getTrue_name());
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.my.jxt.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                setCostomMsg(showMsg.toString());
            }
        }
    }

    private void setCostomMsg(String msg) {
//        if (null != msgText) {
//            msgText.setText(msg);
//            msgText.setVisibility(android.view.View.VISIBLE);
//        }
    }

    private void setTag() {
//        EditText tagEdit = (EditText) findViewById(R.id.et_tag);
        String tag = SaleUserModel.getInstance().loadCurrentSaleUsers().getTrue_name() + "";

        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
//            Toast.makeText(PushSetActivity.this, R.string.error_tag_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!ExampleUtil.isValidTagAndAlias(sTagItme)) {
//                Toast.makeText(PushSetActivity.this, R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));

    }

    private void setAlias() {
        String alias = SaleUserModel.getInstance().loadCurrentSaleUsers().getUser_id() + "";
        if (TextUtils.isEmpty(alias)) {
//            Toast.makeText(MainActivity.this, R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(alias)) {
//            Toast.makeText(MainActivity.this, R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    /**
     * 设置通知提示方式 - 基础属性
     */
    private void setStyleBasic() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(MainActivity.this);
        builder.statusBarDrawable = R.mipmap.ic_launcher;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;  //设置为点击后自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND;  //设置为铃声（ Notification.DEFAULT_SOUND）或者震动（ Notification.DEFAULT_VIBRATE）
        JPushInterface.setPushNotificationBuilder(1, builder);
//        Toast.makeText(PushSetActivity.this, "Basic Builder - 1", Toast.LENGTH_SHORT).show();
    }


    /**
     * 设置通知栏样式 - 定义通知栏Layout
     */
    private void setStyleCustom() {
        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(MainActivity.this, R.layout.customer_notitfication_layout, R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable = R.mipmap.ic_launcher;
        builder.developerArg0 = "developerArg2";
        JPushInterface.setPushNotificationBuilder(2, builder);
//        Toast.makeText(PushSetActivity.this, "Custom Builder - 2", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setAddActionsStyle() {
        MultiActionsNotificationBuilder builder = new MultiActionsNotificationBuilder(MainActivity.this);
        builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "first", "my_extra1");
        builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "second", "my_extra2");
        builder.addJPushAction(R.drawable.jpush_ic_richpush_actionbar_back, "third", "my_extra3");
        JPushInterface.setPushNotificationBuilder(10, builder);

//        Toast.makeText(PushSetActivity.this, "AddActions Builder - 10", Toast.LENGTH_SHORT).show();
    }


    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogInfo.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogInfo.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        LogInfo.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogInfo.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogInfo.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogInfo.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        LogInfo.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogInfo.e(TAG, logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;


    private String TAG;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogInfo.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    LogInfo.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    LogInfo.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
}
